package com.rabbittk.cameraxdemo;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.util.Log;

import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.google.common.util.concurrent.ListenableFuture;

import java.util.concurrent.ExecutionException;

public class BGGLSurfaceView extends GLSurfaceView {

    private static final String TAG = "BGSurfaceView";
    private BGRenderer mbgRenderer;

    public BGGLSurfaceView(Context context) {
        super(context);
        Log.d(TAG, "BGSurfaceView: 1.");
    }

    public BGGLSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        Log.d(TAG, "BGSurfaceView: 2.");

        init();
    }

    private final BGRenderer.Callback mCallback = new BGRenderer.Callback() {
        @Override
        public void onSurfaceChanged() {
            setupCamera();
        }

        @Override
        public void onFrameAvailable() {
            requestRender();
        }
    };

    private void init() {
        setEGLContextClientVersion(2);
        mbgRenderer = new BGRenderer(getContext(), mCallback);
        setRenderer(mbgRenderer);
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }

    private void setupCamera() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(getContext());
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                    Preview preview = new Preview.Builder().build();
                    preview.setSurfaceProvider(mbgRenderer);
                    cameraProvider.unbindAll();
                    Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner) getContext(), CameraSelector.DEFAULT_BACK_CAMERA, preview);
                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        cameraProviderFuture.addListener(runnable, ContextCompat.getMainExecutor(getContext()));
    }
}
